package com.saybiu.controller;

import com.alibaba.fastjson.JSONObject;
import com.saybiu.domain.Picture;
import com.saybiu.exception.ServiceException;
import com.saybiu.response.CommonCode;
import com.saybiu.service.PostService;
import com.saybiu.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: liming
 * @Date: 2021/4/19 21:16
 */

@Controller
public class PostController {
    @Autowired
    private HttpServletRequest request;

    @Resource
    private PostService postService;

    /**
     * 图片缓存控制器 (使用postMan)
     * @return 图片类的集合 (共有两个参数{参数1(pictureUrl):图片缓存路径,参数2(pictureName):图片名称})
     */
    @ResponseBody
    @RequestMapping(value = "cachePicture")
    public List<Picture> cachePictureController(@RequestBody List<Picture> pictureList){

        List<Picture> pictures = postService.addPicture(pictureList, "http://bbs/imamg/lm");
        if(pictures != null){
            return pictures;
        }else {
            throw  new ServiceException(CommonCode.INSERT_ERROR);
        }
    }

    /**
     * 图片上传 并且上传图片文件到指定文件目录中 (前端页面实体测试)
     */
    @ResponseBody
    @RequestMapping(value = "upload")
    public List<Picture> addUserSendPostController(MultipartFile file){
        //拿到完整文件名
        String originalFilename = file.getOriginalFilename();
        //声明文件输出流,准备上传文件
        FileOutputStream out = null;
        // 设置附件的保存地址目录
        String dirPath = request.getServletContext().getRealPath("/static/images");

        //拿到项目全路径
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getSession().getServletContext().getContextPath()).append("/").toString();

        // 如果保存附件的地址不存在，就先创建目录
        File filePath = new File(dirPath);
        if ( !filePath.exists() ) {
            filePath.mkdirs();
        }
        //拼接文件名
        String pictureName = Utils.pictureDate(new Date())+ Utils.creatRandom() + originalFilename ;
        try {
            //创建FileOutputStream流以写入数据到File对象所代表的文件
            out = new FileOutputStream(filePath + "/" + pictureName);
            //上传文件到
            out.write(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //造数据,测试
        List<Picture>  pictureList = new ArrayList<>();
        Picture picture = new Picture();
        picture.setUserId(16);
        picture.setPictureName(pictureName);
        picture.setPictureUrl(dirPath);
        pictureList.add(picture);

        List<Picture> pictures = postService.addPicture(pictureList, tempContextUrl+"static/images");
        if(pictures != null){
            return pictures;
        }else {
            throw  new ServiceException(CommonCode.INSERT_ERROR);
        }
    }
}
